package com.xinchuang.utils;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/9/20 11:25
 */
public class ZipFileWriter {

    public static boolean createZip(List<String> files, String url) {
        FileUtil.mkdir(url);
        // 压缩包的路径和文件名
        String zipFileName = url + "/files.zip";
        try {
            // 创建ZipOutputStream对象
            FileOutputStream fos = new FileOutputStream(zipFileName);
            ZipOutputStream zipOut = new ZipOutputStream(fos);
            // 遍历文件列表，逐个添加到压缩包中
            for (String file : files) {
                File sourceFile = new File(file);
                // 创建ZipEntry对象，并设置文件名
                ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
                zipOut.putNextEntry(zipEntry);
                // 读取文件内容，并写入到压缩包中
                FileInputStream fis = new FileInputStream(sourceFile);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zipOut.write(buffer, 0, length);
                }
                // 关闭当前的ZipEntry
                zipOut.closeEntry();
                fis.close();
            }
            // 关闭ZipOutputStream
            zipOut.close();
            System.out.println("压缩包创建成功！");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
